package com.mingqijia.gassafety.webserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.GetCondtionListVo;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.mapper.AppealLogMapper;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.db.mapper.WorkOrderHistoryMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.RecordLogRequest;
import com.mingqijia.gassafety.webserver.response.AlertLogResponse;
import com.mingqijia.gassafety.webserver.response.CompanyResponse;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.HistoryAlarmAndBrokenResponse;
import com.mingqijia.gassafety.webserver.response.OrganizationResponse;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 报警器设备报警记录 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-08-08
 */
@Slf4j
@Service
public class HistoryAlarmServiceImpl extends ServiceImpl<HistoryAlarmMapper, HistoryAlarm> implements HistoryAlarmService {

    @Autowired
    ConfigureHolder holder;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    HeaderUtil headerUtil;
    @Autowired
    CommonService commonService;
    @Autowired
    EquipmentServiceImpl equipmentServiceImpl;
    @Autowired
    FieldListShowService fieldListShowService;

    @Autowired
    HistoryAlarmService alarmService;

    @Autowired
    HistoryBrokenService brokenService;

    @Autowired
    AppealLogService appealLogService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;

    @Autowired
    AppealLogMapper appealLogMapper;
    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;
    @Autowired
    CompanyService companyService;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Autowired
    ServicePkgRecordService servicePkgRecordService;

    @Autowired
    BusinessNoticeService businessNoticeService;

    @Autowired
    WorkOrderHandleService workOrderHandleService;

    @Override
    public List<HistoryAlarmAndBrokenResponse> getEffectiveData(Integer customerId) {
        List<HistoryAlarm> historyAlarms = this.baseMapper.selectByCustomerId(customerId);

        return CollectionUtils.isEmpty(historyAlarms) ? new ArrayList<>() : historyAlarms.stream().map(historyAlarm -> {
            HistoryAlarmAndBrokenResponse response = new HistoryAlarmAndBrokenResponse();
            BeanUtils.copyProperties(historyAlarm, response);
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public PageUtil<AlertLogResponse> getAlarmList(RecordLogRequest req) {
        List<AlertLogResponse> resultList = new ArrayList<>();
        //要最近的设备信息，从数据库里查询，
        LatestLogListVO vo = new LatestLogListVO();
        //1.查询条件封装
        BeanUtils.copyProperties(req, vo);

        String spId = ApplicationUtils.getWorkingSpId();
        //1.1所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(req.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(req.getSpId());
        }
        vo.setSpIds(spIds);
        Map<String, String> reasonMap = new HashMap<>();
        try {
            List<DictionaryItemRespDTO> alarmReasonDict = holder.getDictionaryByKeyNoCache(
                    Constants.ALARM_REASON, spId);
            reasonMap = alarmReasonDict.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getValue, DictionaryItemRespDTO::getName));
        } catch(Exception e) {
            log.info("getAlarmList-alarmReasonDict-error:{}", e.getMessage());
        }
        Map<String, String> alarmReasonMap = reasonMap;
        Page<HistoryAlarmVo> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryAlarmVo> list = new ArrayList<>();
        //1.2页面模板
        if (req.getTemplateType() == null) {
            req.setTemplateType(headerUtil.getTemplateType());
        }

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());

        if(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()){
            List<HistoryAlarmVo> vccRecord = baseMapper.getVccRecord(vo);
            list = vccRecord;
        }else if(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            list = baseMapper.getAsstRecord(vo);
        }
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap;
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        } else {
            companyNameMap = new HashMap<>();
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap;
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        } else {
            orgSubsCodeMap = new HashMap<>();
        }
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型名称
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKeys(
                    EquipmentType.DICT_CODE, spIds);
            //行业类型名称
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商名称
            ConsoleSkSupplierListResponse supplierList = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", supplierList);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (supplierList != null && supplierList.getCode() == 0 && supplierList.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(supplierList.getData())) {
                supplierListVos = supplierList.getData();
            }
            //组织名称列表
            List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());
            //运营商列表
            List<DictionaryItemRespDTO> operatorList = holder.getDictionaryByKey(Constants.OPERATOR_CODE);
            List<String> query = equipmentServiceImpl.getQueryParams();
            List<Map<String, String>> customerCode = equipmentServiceImpl.dictMap(null, query, null);

            List<AlarmSupplierListVo> finalSupplierListVos = supplierListVos;
            resultList = list.stream().map(historyAlarmVo -> {
                AlertLogResponse response = new AlertLogResponse();
                BeanUtils.copyProperties(historyAlarmVo, response);
                response.setValveInfoId(historyAlarmVo.getValveInfoId());
                response.setXlel(historyAlarmVo.getConcentration() + " %LEL");
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                    response.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                        response.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                    }
                }
                // 报警原因
                response.setValveBrokenInfo(alarmReasonMap.get(historyAlarmVo.getBrokenInfo()) == null ? Constants.BLANK : alarmReasonMap.get(historyAlarmVo.getBrokenInfo()));
                //处理人信息
                if (!StringUtils.isEmpty(historyAlarmVo.getUserName()) && !StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo(historyAlarmVo.getUserName() + "(" + historyAlarmVo.getUserAccount()+ ")");
                }else if (StringUtils.isEmpty(historyAlarmVo.getUserName()) && !StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo( historyAlarmVo.getUserAccount());
                }else if (!StringUtils.isEmpty(historyAlarmVo.getUserName()) && StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo(historyAlarmVo.getUserName());
                }
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyAlarmVo.getAppealStatus()).getMsg());
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyAlarmVo.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyAlarmVo.getIndustryType()));
                //设置设备厂商
                if ( !StringUtils.isEmpty(historyAlarmVo.getEquipmentManufacturer()) ){
                    List<AlarmSupplierListVo> equipmentManufacturers =  finalSupplierListVos.stream().filter(a->a.getAlarmSystemCode().equals(
                            historyAlarmVo.getEquipmentManufacturer())).collect(Collectors.toList());
                    if (!equipmentManufacturers.isEmpty()) {
                        response.setEquipmentManufacturer(equipmentManufacturers.get(0).getMsName());
                    }
                }
                //运营商
                response.setOperators(getName(operatorList, historyAlarmVo.getOperators()));
                //紫荆设备 联系人手机号
                if (historyAlarmVo.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM){
                    response.setContactPhone(historyAlarmVo.getPhone());
                }
                response.setDetectionType(equipmentServiceImpl.setDetection(query, customerCode, response.getDetectionType()));
                //所属组织
                if(!CollectionUtils.isEmpty(organizationList)){
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(historyAlarmVo.getSpId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        response.setSpName(collect.get(0).getSpName());
                    }
                }
                //设备是否携带电磁阀
                response.setHasValve(historyAlarmVo.getValveInfoId() == 0 ? "-":"有");

                //记录中的客户是否是设备上的实时客户
                if(historyAlarmVo.getConsumerId() != 0 && historyAlarmVo.getConsumerId().equals(historyAlarmVo.getLatestConsumerId())){
                    response.setBinded(1);
                }else {
                    response.setBinded(0);
                }
                //irs上报需要用到
                response.setTime(DateUtils.format(historyAlarmVo.getLatestTime(),"yyyy-MM-dd HH:mm:ss"));
                return response;
            }).collect(Collectors.toList());
        }
        List<FieldListShowResponse> responses = fieldListShowService.queryListShowByShowStatus(PageListCode.ALARM_RECORD.getCode(), spId);
        List<String> fields = responses.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
        List<String> titles = responses.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
        List<PageColumns> pageColumns = new ArrayList<>();
        if(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType() ){
            pageColumns = PageColumnConst.add(titles.toArray(new String[]{}), fields.toArray(new String[]{}), ApplicationUtils.getWorkingSpId());
        }else if(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()){
            pageColumns = PageColumnConst.add(PageColumnConst.AlertVccUserTitles, PageColumnConst.AlertVccUserIndices, ApplicationUtils.getWorkingSpId());
        }
        List<Integer> consumerIds= resultList.stream().map(AlertLogResponse::getConsumerId).collect(Collectors.toList());
        List<Integer> valveInfoIds = list.stream().map(HistoryAlarmVo::getValveInfoId).collect(Collectors.toList());

        commonService.loadFieldAndPackaging(resultList, AlertLogResponse.class, consumerIds, valveInfoIds, null, spId,PageListCode.ALARM_RECORD.getCode());
        log.info("getAlarmList-resultList:{}", JSONObject.toJSONString(resultList));
        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList, pageColumns);

        return pageInfo;
    }

    private String getName(List<DictionaryItemRespDTO> list, String  value) {
        if( !CollectionUtils.isEmpty(list)){
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)){
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

    @Override
    public Map<String, Integer> getConditionList(Integer isSpecialized) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        Map<String, Integer> map = new HashMap<>();
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);

        //诉求状态：0待处理 1工单处理中 2已处理 3工单处理完成
        GetCondtionListVo conditionList = this.baseMapper.getConditionList(spIds, userFuncCodePermission.getFuncCodes());
        Integer all = conditionList.getNumber();
        Integer handling = conditionList.getHandling();
        Integer hasHandled = conditionList.getHasHandled();
        Integer finishing = conditionList.getFinishing();
        Integer unclosed = conditionList.getUnclosed();
        Integer closed = conditionList.getClosed();
        Integer handleInstall = conditionList.getHandleInstall();
        Integer handlerTest = conditionList.getHandlerTest();
        Integer unNeedHandle = conditionList.getUnNeedHandle();
        Integer waitHandle = 0;
        if (all == null) {
            all = 0;
        }
        if (handling == null) {
            handling = 0;
        }
        if (hasHandled == null) {
            hasHandled = 0;
        }
        if (finishing == null) {
            finishing = 0;
        }
        if (unclosed == null) {
            unclosed = 0;
        }
        if (closed == null) {
            closed = 0;
        }
        if (handleInstall == null) {
            handleInstall = 0;
        }
        if (handlerTest == null) {
            handlerTest = 0;
        }
        if (unNeedHandle == null) {
            unNeedHandle = 0;
        }
        waitHandle = all - handling - hasHandled - finishing - unclosed - closed - handleInstall - handlerTest - unNeedHandle;

        if(isSpecialized == 1){
            map.put("待处理", waitHandle);
            map.put("未办结", handling + unclosed);
            map.put("已办结", hasHandled + finishing + closed + handleInstall + handlerTest + unNeedHandle);
        }else {
            map.put("未处理", waitHandle);
            map.put("处理中", handling + unclosed);
            map.put("处理完成", hasHandled + finishing+closed + handleInstall + handlerTest + unNeedHandle);
        }
        return map;

    }


    public void appealIntallRecord(WorkOrderHistory workOrderHistory, Long id, Integer type) {
        log.info("appealIntallRecord-workOrderHistory:{},id:{},type:{}",JSONObject.toJSON(workOrderHistory),id,type);

        try {
            List<AppealLog> appealLogs = new ArrayList<>();
            AppealLog appealLog = new AppealLog();
            appealLog.setAppealType(type);
            appealLog.setAlarmBrokenId(id);
            appealLog.setAppealStatus(AppealStateEnum.HANDLED_INSTALL.getCode());
            appealLog.setUserName("安装调试");
            appealLog.setUserAccount("");
            appealLog.setIsDeleted(false);
            appealLog.setSpId(workOrderHistory.getSpId());
            appealLogs.add(appealLog);
            appealLogService.saveBatch(appealLogs);
            // 更新报警/故障信息记录主表
            if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarm = new HistoryAlarm();
                historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                historyAlarm.setAppealResult(appealLog.getAppealResult());
                historyAlarm.setUserName(appealLog.getUserName());
                historyAlarm.setUserAccount(appealLog.getUserAccount());
                historyAlarm.setAppealTime(appealLog.getCreatedAt());
                boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
            } else if (appealLog.getAppealType() == 1) {
                LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                HistoryBroken historyBroken = new HistoryBroken();
                historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyBroken.setAppealStatus(appealLog.getAppealStatus());
                historyBroken.setAppealResult(appealLog.getAppealResult());
                historyBroken.setUserName(appealLog.getUserName());
                historyBroken.setUserAccount(appealLog.getUserAccount());
                historyBroken.setAppealTime(appealLog.getCreatedAt());
                boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
            }
        } catch (Exception e) {
            log.error("appealIntallRecord-error:{}",e);
        }
    }

    /**
     * 当报警器恢复时自动处理s
     * @param alarmBrokenInfo 报警或故障信息
     * @param type 0:报警 1:故障
     */
    public void alarmBrokenAutoHandelWhenRecovery(Object alarmBrokenInfo, Integer type) {
        log.info("alarmBrokenAutoHandelWhenRecovery-workOrderHistory:{},type:{}",JSONObject.toJSON(alarmBrokenInfo),type);
        String servicePkgContent = "";
        String spId = "";
        int consumerId = 0;
        String imei = "";
        if (type == 0) {
            servicePkgContent = ServicePkgEnum.ALERT_UNNEED_HANDEL.getCode();
            HistoryAlarm historyAlarm = (HistoryAlarm)alarmBrokenInfo;
            spId = historyAlarm.getSpId();
            consumerId = historyAlarm.getConsumerId();
            imei = historyAlarm.getIMEI();
        } else if (type == 1) {
            servicePkgContent = ServicePkgEnum.BROKEN_UNNEED_HANDEL.getCode();
            HistoryBroken historyBroken = (HistoryBroken)alarmBrokenInfo;
            spId = historyBroken.getSpId();
            consumerId = historyBroken.getConsumerId();
            imei = historyBroken.getIMEI();
        } else {
            log.info("alarmBrokenAutoHandelWhenRecovery error type:{}", type);
            return;
        }
        Boolean servicePkgModeSwitch = businessNoticeService.switchValueByCode(
                BusinessNoticeParam.DIFFERENT_SERVICE_PACKAGE_MODE.getCode(),
                spId
        );
        boolean servicePkgFlag = true;
        if (!servicePkgModeSwitch){
            log.info("alarmBrokenAutoHandelWhenRecovery==>>开关未开启");
            servicePkgFlag = false;
        }
        if(!servicePkgRecordService.checkOwnerServiceContentCode(
                spId,
                consumerId,
                -1,
                imei,
                servicePkgContent
        )){
            log.info("alarmBrokenAutoHandelWhenRecovery=>报警-客户:{},imei:{},servicePkgContent:{}未开启报警恢复,报警记录自动处理功能", consumerId, imei, servicePkgContent);
            servicePkgFlag = false;
        }
        if (!servicePkgFlag){
            if (type == 0) {
                workOrderHandleService.cancelOrder((HistoryAlarm)alarmBrokenInfo);
            }else {
                workOrderHandleService.cancelOrder((HistoryBroken)alarmBrokenInfo);
            }
            return;
        }
        try {
            long alarmBrokenId;
            String appealResult = "";
            if (type == 0) {
                HistoryAlarm record = getImeiLastHistoryAlarm(spId,imei,consumerId);
                if (record == null) {
                    return;
                }
                if( record.getAppealStatus()>0 ){
                    log.info("alarmBrokenAutoHandelWhenRecovery:告警-非待处理状态，不能自动处理");
                    return;
                }
                if( record.getWorkorderId()>0 ){
                    log.info("alarmBrokenAutoHandelWhenRecovery:告警-已转工单处理，不能自动处理");
                    return;
                }
                alarmBrokenId = record.getId();
                appealResult = "设备上报报警恢复,无需处理";
            } else {
                HistoryBroken record = brokenService.getImeiLastHistoryBroken(spId,imei,consumerId);
                if (record == null) {
                    return;
                }
                if( record.getAppealStatus()>0 ){
                    log.info("alarmBrokenAutoHandelWhenRecovery:故障-非待处理状态，不能自动处理");
                    return;
                }
                if( record.getWorkorderId()>0 ){//非转工单处理
                    log.info("alarmBrokenAutoHandelWhenRecovery:故障-已转工单处理，不能自动处理");
                    return;
                }
                alarmBrokenId = record.getId();
                appealResult = "设备上报故障恢复,无需处理";
            }
            AppealLog appealLog = new AppealLog();
            appealLog.setAlarmBrokenId(alarmBrokenId);
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_8);
            appealLog.setAppealResult(appealResult);
            appealLog.setSpId(spId);
            appealLog.setUserName("报警监控系统");
            appealLog.setUserAccount("");
            appealLog.setAppealType(type);
            appealLogService.save(appealLog);
            // 更新报警/故障信息记录主表
            if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarm = new HistoryAlarm();
                historyAlarm.setValveBrokenInfo("");
                historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                historyAlarm.setAppealResult(appealLog.getAppealResult());
                historyAlarm.setUserName(appealLog.getUserName());
                historyAlarm.setUserAccount(appealLog.getUserAccount());
                historyAlarm.setAppealTime(appealLog.getCreatedAt());
                boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                log.info("alarmBrokenAutoHandelWhenRecovery->工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
            } else  if (appealLog.getAppealType() == 1) {
                LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                HistoryBroken historyBroken = new HistoryBroken();
                historyBroken.setValveBrokenInfo("");
                historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyBroken.setAppealStatus(appealLog.getAppealStatus());
                historyBroken.setAppealResult(appealLog.getAppealResult());
                historyBroken.setUserName(appealLog.getUserName());
                historyBroken.setUserAccount(appealLog.getUserAccount());
                historyBroken.setAppealTime(appealLog.getCreatedAt());
                boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                log.info("alarmBrokenAutoHandelWhenRecovery->工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
            }
        } catch (Exception e) {
            log.error("alarmBrokenAutoHandelWhenRecovery-error",e);
        }
    }

    @Override
    public HistoryAlarm getImeiLastHistoryAlarm(String spId,String imei,Integer consumerId){
        LambdaQueryWrapper<HistoryAlarm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HistoryAlarm::getIMEI,imei);
        queryWrapper.eq(HistoryAlarm::getSpId,spId);
        queryWrapper.eq(HistoryAlarm::getConsumerId,consumerId);
        queryWrapper.eq(HistoryAlarm::getIsDeleted, 0);
        queryWrapper.orderByDesc(HistoryAlarm::getId);
        queryWrapper.last("LIMIT 1");
        List<HistoryAlarm> historyAlarmList = historyAlarmService.getBaseMapper().selectList(queryWrapper);
        log.info("alarmBrokenAutoHandelWhenRecovery historyAlarmList:{}", JSONObject.toJSONString(historyAlarmList));
        if (historyAlarmList == null || historyAlarmList.isEmpty()) {
            return null;
        }
        return historyAlarmList.get(0);
    }



}
